#include "Engine.h"
#include "Window.h"
#include "Renderer.h"
#include "Game.h"
#include <sstream>

using namespace pg1;
Engine::Engine(HINSTANCE hInstance,unsigned int width, unsigned int heigth)
:
e_hInstance (hInstance),
e_width(width),
e_heigth(heigth),
window(new Window(hInstance)),
renderer(new Renderer()),
game(NULL),
m_pkInput( new DirectInput()),
m_pkTimer( new Timer() )
{

}
Engine::~Engine(){
	
	delete m_pkTimer;
	m_pkTimer=NULL;

	delete m_pkInput;
	m_pkInput= NULL;

	delete renderer;
	renderer = NULL;

	delete window;
	window = NULL;
}

bool Engine::init(){

	
	//HWND hWnd;

	/*if(!window->init())
		return false;*/

	if(window->createWindows(e_width,e_heigth) == TRUE && renderer->init(window->getHWnd()) == TRUE && m_pkInput->init(e_hInstance,window->getHWnd()))
		return true;

	/*if(!window->createWindows(e_width, e_heigth))
		return false;

	if(!renderer->init(window->getHWnd()))
		return false;
		*/
	return false;
}

void Engine::run(){

	bool bDone = false;
	MSG kMsg;
	if(!game){
		return;
	}
	if(!game->init(*renderer)){
		return;
	}

	m_pkTimer->firstMeasure();
	while(!bDone){

		m_pkTimer->measure();

		//update FPSs
		  static std::stringstream Title;
		Title.str("");
		Title << window->getWindowName()<< " (" << m_pkTimer->fps() << " FPS)";

		window->setWindowName(Title.str());

		m_pkInput->reacquire(); 
		renderer->beginFrame();
		game->frame(*renderer,*m_pkInput,*m_pkTimer);
		//renderer->beginFrame();
		renderer->endFrame();

		/*if(PeekMessage(&kMsg, NULL, 0, 0, PM_REMOVE)){
			switch(kMsg.message){
				case WM_KEYDOWN:
				{
					int iKeyCode = (int)kMsg.wParam;

					switch (iKeyCode)
					{
						case VK_ESCAPE:
   							bDone = true;
							break;
					}
					break;
				}
			}

			TranslateMessage(&kMsg);
			DispatchMessage(&kMsg);
		}*/

		if(PeekMessage(&kMsg,NULL,0,0,PM_REMOVE))
		{
		// Pasamos el mensaje de vuelta a Windows
			TranslateMessage(&kMsg);
			DispatchMessage(&kMsg);
		}
		if(kMsg.message == WM_QUIT)
			bDone = true;

	}
}
